package com.example.weight.greenSeasons.flocculation;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.arrayAdapter.MyAdapter;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.compost.duifeiguzhangjilu;
import com.example.weight.greenSeasons.compost.duifeiyuebaoyang;
import com.example.weight.greenSeasons.waterDeal.RepairTable;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class xuningguzhang extends AppCompatActivity {
    private TitleBar titleBar;
    private String name, equipmentNameText, factory;

    private Spinner equipment_name;
    private EditText fault_description;
    private EditText repair_personInCharge;
    private EditText fault_analysis;
    private EditText repair_method;
    private EditText method_person;
    private EditText check_person;

    private EditText Downtime;
    private EditText start_time;
    private EditText end_time;
    private EditText recovery_time;

    private SharedPreferences preferences;
    private ItemAdapter personAdapter;
    private List<String> personList;
    private EditText repair_person;
    private PopupWindow personPopupWindow;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");// HH:mm:ss

    //备选设备列表
    private List<String> equipmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuningguzhang);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                xuningguzhang.this.finish();
            }
            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

        //4个日期时间
        Downtime=findViewById(R.id.Downtime);
        start_time=findViewById(R.id.start_time);
        end_time=findViewById(R.id.end_time);
        recovery_time=findViewById(R.id.recovery_time);

        Downtime.setText(simpleDateFormat.format(new Date()));

        //7个输入项
        equipment_name = findViewById(R.id.equipmemt_name);
        fault_description = findViewById(R.id.fault_description);
        repair_personInCharge = findViewById(R.id.repair_personInCharge);
        fault_analysis = findViewById(R.id.fault_analysis);
        repair_method = findViewById(R.id.repair_method);
        method_person = findViewById(R.id.method_person);
        check_person = findViewById(R.id.check_person);

        equipmentList = new ArrayList<>();


        // 设置输入记录缓存
        preferences = getSharedPreferences("activity_repair_table", Context.MODE_PRIVATE);
        repair_person = findViewById(R.id.repair_person);
        personList = new ArrayList<>(preferences.getStringSet("personList", new HashSet<>()));
        List<Item> personItemList = new ArrayList<>();
        // Item类型list初始化
        for (String itemName : personList) {
            personItemList.add(new Item(itemName, R.drawable.ic_clear));
        }
        // 创建ListView
        personAdapter = new ItemAdapter(this, R.layout.adapter_item, personItemList);
        ListView personListView = new ListView(this);
        personListView.setAdapter(personAdapter);
        personListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (personAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = personAdapter.getList();
                personList.clear();
                for (Item item : tempItemList) {
                    personList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = personList.get(position);
            repair_person.setText(result);
            personPopupWindow.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        personPopupWindow = new PopupWindow(personListView ,width,height);
        // 设置点击外部区域可以取消popupWindow
        personPopupWindow.setOutsideTouchable(true);

        repair_person.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                personPopupWindow.showAsDropDown(repair_person);
            }
        });

        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/flocculationProduceFault/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id") && data.getString("factory").equals(factory)) {
//                                    equipment_name.setPrompt(data.getString("equipmentname"));
                                    Downtime.setText(data.getString("downtime"));
//                                    operate_person.setText(data.getString("operatePerson"));
                                    fault_description.setText(data.getString("faultDescription"));
                                    start_time.setText(data.getString("startTime"));
                                    end_time.setText(data.getString("endTime"));
                                    repair_personInCharge.setText(data.getString("personincharge"));
                                    repair_person.setText(data.getString("repairPerson"));
                                    fault_analysis.setText(data.getString("faultAnalysis"));
                                    repair_method.setText(data.getString("repairMethod"));
                                    method_person.setText(data.getString("methodPerson"));
                                    recovery_time.setText(data.getString("recoveryTime"));
                                    check_person.setText(data.getString("checkPerson"));
                                    Toast.makeText(xuningguzhang.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                Downtime.setHint("2020-01-01 00:00");
                                start_time.setHint("2020-01-01 00:00");
                                end_time.setHint("2020-01-01 00:00");
                                recovery_time.setHint("2020-01-01 00:00");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningguzhang.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);



        //获取待维修设备列表
        String url2 = Config.url + "/sjq/flocculationProduceFault/findFaultEquipList" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        equipmentList.add(data.getString(i));
                                    }
                                    equipmentList.add("  ");//这句千万别删
                                    Log.d("equipmentList", equipmentList.toString());
                                    MyAdapter adapter = new MyAdapter(xuningguzhang.this, equipmentList);
                                    equipment_name.setAdapter(adapter);
                                    equipment_name.setSelection(0,true);
                                    equipment_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            equipmentNameText = equipmentList.get(position);
                                            Toast.makeText(xuningguzhang.this, equipmentNameText, Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {

                                        }
                                    });
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningguzhang.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);
    }

//    @SuppressLint("ResourceType")
//    public void chooseStopDate(View view) {
//        Calendar calendar=Calendar.getInstance();
//        new DatePickerDialog(xuningguzhang.this,2,
//                new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year,
//                                          int month, int day) {
//                        // TODO Auto-generated method stub
//                        Integer mYear = year;
//                        Integer mMonth = month;
//                        Integer mDay = day;
//                        // 更新EditText控件日期 小于10加0
//                        new TimePickerDialog(xuningguzhang.this,2, new TimePickerDialog.OnTimeSetListener() {
//                            @Override
//                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//                                Integer mhourOfDay  = hourOfDay;   //得到小时
//                                Integer mminute  = minute;            //得到分钟
//                                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
//                                Downtime.setText(new StringBuilder()
//                                        .append(mYear)
//                                        .append("-")
//                                        .append((mMonth + 1) < 10 ? "0"
//                                                + (mMonth + 1) : (mMonth + 1))
//                                        .append("-")
//                                        .append((mDay < 10) ? "0" + mDay : mDay)
//                                        .append(" ")
//                                        .append(String.format("%02d",hourOfDay)).append(":").append(String.format("%02d",minute)));
//                            }
//                        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MONTH), true).show();
//
//                    }
//                }, calendar.get(Calendar.YEAR), calendar
//                .get(Calendar.MONTH), calendar
//                .get(Calendar.DAY_OF_MONTH)).show();
//    }

    @SuppressLint("ResourceType")
    public void chooseStartDate(View view) {
        Calendar calendar=Calendar.getInstance();
        new DatePickerDialog(xuningguzhang.this,2,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        Integer mYear = year;
                        Integer mMonth = month;
                        Integer mDay = day;
                        // 更新EditText控件日期 小于10加0
                        new TimePickerDialog(xuningguzhang.this,2, new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                Integer mhourOfDay  = hourOfDay;   //得到小时
                                Integer mminute  = minute;            //得到分钟
                                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                                start_time.setText(new StringBuilder()
                                        .append(mYear)
                                        .append("-")
                                        .append((mMonth + 1) < 10 ? "0"
                                                + (mMonth + 1) : (mMonth + 1))
                                        .append("-")
                                        .append((mDay < 10) ? "0" + mDay : mDay)
                                        .append(" ")
                                        .append(String.format("%02d",hourOfDay)).append(":").append(String.format("%02d",minute)));
                            }
                        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MONTH), true).show();

                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH)).show();
    }

    @SuppressLint("ResourceType")
    public void chooseEndDate(View view) {
        Calendar calendar=Calendar.getInstance();
        new DatePickerDialog(xuningguzhang.this,2,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        Integer mYear = year;
                        Integer mMonth = month;
                        Integer mDay = day;
                        // 更新EditText控件日期 小于10加0
                        new TimePickerDialog(xuningguzhang.this,2, new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                Integer mhourOfDay  = hourOfDay;   //得到小时
                                Integer mminute  = minute;            //得到分钟
                                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                                end_time.setText(new StringBuilder()
                                        .append(mYear)
                                        .append("-")
                                        .append((mMonth + 1) < 10 ? "0"
                                                + (mMonth + 1) : (mMonth + 1))
                                        .append("-")
                                        .append((mDay < 10) ? "0" + mDay : mDay)
                                        .append(" ")
                                        .append(String.format("%02d",hourOfDay)).append(":").append(String.format("%02d",minute)));
                            }
                        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MONTH), true).show();

                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH)).show();
    }

    @SuppressLint("ResourceType")
    public void chooseRestoreDate(View view) {
        Calendar calendar=Calendar.getInstance();
        new DatePickerDialog(xuningguzhang.this,2,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        Integer mYear = year;
                        Integer mMonth = month;
                        Integer mDay = day;
                        // 更新EditText控件日期 小于10加0
                        new TimePickerDialog(xuningguzhang.this, 2,new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                Integer mhourOfDay  = hourOfDay;   //得到小时
                                Integer mminute  = minute;            //得到分钟
                                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                                recovery_time.setText(new StringBuilder()
                                        .append(mYear)
                                        .append("-")
                                        .append((mMonth + 1) < 10 ? "0"
                                                + (mMonth + 1) : (mMonth + 1))
                                        .append("-")
                                        .append((mDay < 10) ? "0" + mDay : mDay)
                                        .append(" ")
                                        .append(String.format("%02d",hourOfDay)).append(":").append(String.format("%02d",minute)));
                            }
                        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MONTH), true).show();

                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH)).show();
    }


    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (equipmentNameText == null) {
            Toast.makeText(this, "请选择设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if(Downtime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写停机时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (fault_description.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障情况描述", Toast.LENGTH_SHORT).show();
            return;
        }
        if (start_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (end_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repair_personInCharge.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修负责人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repair_person.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修人员", Toast.LENGTH_SHORT).show();
            return;
        }
        if (fault_analysis.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障原因分析", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repair_method.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修方法", Toast.LENGTH_SHORT).show();
            return;
        }
        if (method_person.getText().toString().equals("")) {
            Toast.makeText(this, "请填写方法提出人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (recovery_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障恢复时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (check_person.getText().toString().equals("")) {
            Toast.makeText(this, "请填写检查人", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //输入缓存
                    SharedPreferences.Editor editor = preferences.edit();
                    // 若有进行删除操作，更新personList
                    List<Item> tempPersonList = personAdapter.getList();
                    if (tempPersonList.size() != personList.size()) {
                        personList.clear();
                        for (Item item : tempPersonList) {
                            personList.add(item.getName());
                        }
                    }
                    // 判断该输入框内容是否已存在，不存在则加入
                    String currentBatch = repair_person.getText().toString();
                    if (!currentBatch.equals("") && !personList.contains(currentBatch)) {
                        personList.add(currentBatch);
                    }


                    editor.putStringSet("personList", new HashSet<>(personList));
                    editor.apply();

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/flocculationProduceFault/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("LB", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(xuningguzhang.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(xuningguzhang.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(xuningguzhang.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("LB", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipmentName",  equipmentNameText);
                            map.put("Downtime", Downtime.getText().toString());
                            map.put("fault_description", fault_description.getText().toString());
                            map.put("start_time", start_time.getText().toString());
                            map.put("end_time", end_time.getText().toString());
                            map.put("personIncharge", repair_personInCharge.getText().toString());
                            map.put("repair_person", repair_person.getText().toString());
                            map.put("fault_analysis", fault_analysis.getText().toString());
                            map.put("repair_method", repair_method.getText().toString());
                            map.put("method_person", method_person.getText().toString());
                            map.put("recovery_time", recovery_time.getText().toString());
                            map.put("check_person", check_person.getText().toString());
                            map.put("operate_person",name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }


    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}